package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.mapper.GradeMapper;
import com.demo.mapper.StudentMapper;
import com.demo.mapper.ScheduleMapper;
import com.demo.mapper.ClazzMapper;
import com.demo.mapper.ClazzTeacherMapper;
import com.demo.mapper.TeacherMapper;
import com.demo.mapper.TeacherPreferenceMapper;
import com.demo.mapper.CourseMapper;
import com.demo.mapper.StudentCourseMapper;
import com.demo.pojo.dto.ScheduleListDTO;
import com.demo.pojo.entity.Grade;
import com.demo.pojo.entity.Student;
import com.demo.pojo.entity.Clazz;
import com.demo.pojo.entity.ClazzTeacher;
import com.demo.pojo.entity.Teacher;
import com.demo.pojo.entity.TeacherPreference;
import com.demo.pojo.entity.Course;
import com.demo.pojo.entity.StudentCourse;
import com.demo.service.TeacherUserService;
import com.demo.service.ScheduleService;
import java.util.Date;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 教师用户服务实现类
 */
@Service
public class TeacherUserServiceImpl implements TeacherUserService {
    
    @Autowired
    private TeacherMapper teacherMapper;
    
    @Autowired
    private TeacherPreferenceMapper teacherPreferenceMapper;
    
    @Autowired
    private ScheduleService scheduleService;
    
    @Autowired
    private ScheduleMapper scheduleMapper;
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Autowired
    private ClazzMapper clazzMapper;
    
    @Autowired
    private ClazzTeacherMapper clazzTeacherMapper;
    
    @Autowired
    private GradeMapper gradeMapper;
    
    @Autowired
    private CourseMapper courseMapper;
    
    @Autowired
    private StudentCourseMapper studentCourseMapper;
    
    @Override
    public Teacher teacherLogin(String teNo, String password) {
        if (teNo == null || teNo.trim().isEmpty()) {
            throw new RuntimeException("教师工号不能为空");
        }
        
        if (password == null || password.trim().isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }
        
        // 使用BINARY确保工号区分大小写（安全性要求）
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("BINARY te_no = {0}", teNo);
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        
        if (teacher == null) {
            throw new RuntimeException("教师工号不存在");
        }
        
        // 验证身份证后六位
        String idCard = teacher.getTeIdCard();
        if (idCard == null || idCard.length() < 6) {
            throw new RuntimeException("教师身份证信息不完整");
        }
        
        String lastSixDigits = idCard.substring(idCard.length() - 6);
        if (!password.equals(lastSixDigits)) {
            throw new RuntimeException("密码错误，请输入身份证后六位");
        }
        
        return teacher;
    }
    
    @Override
    public Teacher getTeacherInfo(Long teacherId) {
        return teacherMapper.selectById(teacherId);
    }
    
    @Override
    public boolean updateTeacherInfo(Teacher teacher) {
        return teacherMapper.updateById(teacher) > 0;
    }
    
    @Override
    public List<ScheduleListDTO> getTeacherSchedule(Long teacherId, String semester) {
        return scheduleService.getTeacherSchedule(teacherId, semester);
    }
    
    @Override
    public List<ScheduleListDTO> getTeacherWeekSchedule(Long teacherId, String semester, Integer weekNo) {
        // 这里需要根据周次过滤课表
        List<ScheduleListDTO> allSchedules = scheduleService.getTeacherSchedule(teacherId, semester);
        // 简化实现，实际需要根据时间段表查询周次
        return allSchedules;
    }
    
    @Override
    public List<ScheduleListDTO> getTeacherTodaySchedule(Long teacherId, String semester, Integer weekNo, Integer dayOfWeek) {
        // 这里需要根据星期几过滤课表
        List<ScheduleListDTO> allSchedules = scheduleService.getTeacherSchedule(teacherId, semester);
        // 简化实现，实际需要根据时间段表查询星期几
        return allSchedules;
    }
    
    @Override
    public boolean applyScheduleChange(Long scheduleId, String reason, Long newTimeSlotId, Long newClassroomId) {
        // 调课申请逻辑
        // 这里需要创建调课申请记录，等待管理员审批
        return true; // 简化实现
    }
    
    @Override
    public Map<String, Object> getTeacherWorkloadStats(Long teacherId, String semester) {
        try {
            System.out.println("===== 获取教师工作量统计 =====");
            System.out.println("教师ID: " + teacherId + ", 学期: " + semester);
            
            // 1. 获取教师的所有排课（先尝试指定学期，如果没数据则获取全部）
            List<ScheduleListDTO> schedules = scheduleService.getTeacherSchedule(teacherId, semester);
            System.out.println("指定学期排课数量: " + schedules.size());
            
            // 如果指定学期没有数据，尝试获取所有学期的数据
            if (schedules.isEmpty() && semester != null && !semester.isEmpty()) {
                System.out.println("指定学期无数据，尝试获取所有学期...");
                schedules = scheduleService.getTeacherSchedule(teacherId, null);
                System.out.println("所有学期排课数量: " + schedules.size());
            }
            
            System.out.println("最终使用排课数量: " + schedules.size());
            
            Map<String, Object> stats = new HashMap<>();
            
            if (schedules == null || schedules.isEmpty()) {
                stats.put("totalHours", 0);
                stats.put("courseCount", 0);
                stats.put("studentCount", 0);
                stats.put("avgWeeklyHours", 0);
                stats.put("courseDetails", new ArrayList<>());
                stats.put("weeklyDistribution", new ArrayList<>());
                return stats;
            }
            
            // 2. 统计不同的课程（按课程ID去重）
            Set<Long> uniqueCourses = new HashSet<>();
            for (ScheduleListDTO schedule : schedules) {
                if (schedule.getCourseId() != null) {
                    uniqueCourses.add(schedule.getCourseId());
                }
            }
            int courseCount = uniqueCourses.size();
            System.out.println("不同课程数: " + courseCount);
            
            // 3. 计算总课时（每个排课默认2学时，一周重复16次）
            int totalHours = schedules.size() * 2 * 16;
            System.out.println("总课时: " + totalHours);
            
            // 4. 统计学生人数（通过班级）
            Set<Long> uniqueClazzes = new HashSet<>();
            for (ScheduleListDTO schedule : schedules) {
                if (schedule.getClazzId() != null) {
                    uniqueClazzes.add(schedule.getClazzId());
                }
            }
            
            int studentCount = 0;
            for (Long clazzId : uniqueClazzes) {
                QueryWrapper<Student> wrapper = new QueryWrapper<>();
                wrapper.eq("clazz_id", clazzId);
                studentCount += studentMapper.selectCount(wrapper);
            }
            System.out.println("学生总数: " + studentCount);
            
            // 5. 计算平均周课时（16周学期）
            double avgWeeklyHours = schedules.size() * 2.0;
            System.out.println("平均周课时: " + avgWeeklyHours);
            
            // 6. 构建课程详细信息列表
            List<Map<String, Object>> courseDetails = new ArrayList<>();
            
            // 首先获取教师关联的所有班级（通过clazz_teacher表）
            Set<Long> allClazzIds = new HashSet<>();
            
            // 从排课记录中获取班级
            for (ScheduleListDTO schedule : schedules) {
                if (schedule.getClazzId() != null) {
                    allClazzIds.add(schedule.getClazzId());
                }
            }
            
            // 从clazz_teacher关联表中获取班级
            QueryWrapper<ClazzTeacher> ctWrapper = new QueryWrapper<>();
            ctWrapper.eq("teacher_id", teacherId);
            List<ClazzTeacher> clazzTeachers = clazzTeacherMapper.selectList(ctWrapper);
            for (ClazzTeacher ct : clazzTeachers) {
                if (ct.getClazzId() != null) {
                    allClazzIds.add(ct.getClazzId());
                }
            }
            
            System.out.println("从clazz_teacher获取的班级IDs: " + allClazzIds);
            
            // 🔥 如果只有1个班级，自动查找同年级的其他班级
            if (allClazzIds.size() == 1) {
                System.out.println(">>> 只有1个班级，自动查找同年级班级...");
                Long firstClazzId = allClazzIds.iterator().next();
                Clazz firstClazz = clazzMapper.selectById(firstClazzId);
                if (firstClazz != null && firstClazz.getClazzName() != null) {
                    String clazzName = firstClazz.getClazzName();
                    System.out.println(">>> 当前班级: " + clazzName);
                    
                    // 提取前缀（如"软件工程2023-"）
                    if (clazzName.contains("-")) {
                        String prefix = clazzName.substring(0, clazzName.lastIndexOf("-") + 1);
                        System.out.println(">>> 班级前缀: " + prefix);
                        
                        // 查找所有同前缀的班级
                        QueryWrapper<Clazz> clazzWrapper = new QueryWrapper<>();
                        clazzWrapper.like("clazz_name", prefix);
                        List<Clazz> sameGradeClazzes = clazzMapper.selectList(clazzWrapper);
                        
                        if (sameGradeClazzes != null) {
                            System.out.println(">>> 找到同年级班级: " + sameGradeClazzes.size() + "个");
                            for (Clazz clazz : sameGradeClazzes) {
                                allClazzIds.add(clazz.getClazzId());
                                System.out.println(">>>   - " + clazz.getClazzName() + " (ID: " + clazz.getClazzId() + ")");
                            }
                        }
                    }
                }
            }
            
            System.out.println("最终所有班级IDs: " + allClazzIds + " (共" + allClazzIds.size() + "个)");
            
            // 为每个班级创建详细信息
            for (Long clazzId : allClazzIds) {
                Clazz clazz = clazzMapper.selectById(clazzId);
                if (clazz == null) continue;
                
                // 查找该班级的排课记录
                List<ScheduleListDTO> clazzSchedules = new ArrayList<>();
                Set<Long> clazzCourseIds = new HashSet<>();
                
                for (ScheduleListDTO schedule : schedules) {
                    if (schedule.getClazzId() != null && schedule.getClazzId().equals(clazzId)) {
                        clazzSchedules.add(schedule);
                        if (schedule.getCourseId() != null) {
                            clazzCourseIds.add(schedule.getCourseId());
                        }
                    }
                }
                
                // 如果该班级有排课记录，按课程分别统计
                if (!clazzSchedules.isEmpty()) {
                    for (Long courseId : clazzCourseIds) {
                        List<ScheduleListDTO> courseClassSchedules = new ArrayList<>();
                        ScheduleListDTO firstSchedule = null;
                        
                        for (ScheduleListDTO schedule : clazzSchedules) {
                            if (schedule.getCourseId() != null && schedule.getCourseId().equals(courseId)) {
                                courseClassSchedules.add(schedule);
                                if (firstSchedule == null) {
                                    firstSchedule = schedule;
                                }
                            }
                        }
                        
                        if (firstSchedule != null) {
                            Map<String, Object> detail = new HashMap<>();
                            detail.put("courseName", firstSchedule.getCourseName());
                            detail.put("className", clazz.getClazzName());
                            detail.put("courseType", "必修");
                            detail.put("credits", 4);
                            detail.put("totalHours", courseClassSchedules.size() * 2 * 16);
                            detail.put("completedHours", courseClassSchedules.size() * 2 * 8);
                            detail.put("remainingHours", courseClassSchedules.size() * 2 * 8);
                            
                            // 统计班级学生数
                            QueryWrapper<Student> wrapper = new QueryWrapper<>();
                            wrapper.eq("clazz_id", clazzId);
                            int classStudentCount = (int) studentMapper.selectCount(wrapper).longValue();
                            detail.put("studentCount", classStudentCount);
                            detail.put("progress", 50);
                            
                            courseDetails.add(detail);
                        }
                    }
                } else {
                    // 即使没有排课记录，也显示该班级
                    Map<String, Object> detail = new HashMap<>();
                    detail.put("courseName", "暂无排课");
                    detail.put("className", clazz.getClazzName());
                    detail.put("courseType", "-");
                    detail.put("credits", 0);
                    detail.put("totalHours", 0);
                    detail.put("completedHours", 0);
                    detail.put("remainingHours", 0);
                    
                    // 统计班级学生数
                    QueryWrapper<Student> wrapper = new QueryWrapper<>();
                    wrapper.eq("clazz_id", clazzId);
                    int classStudentCount = (int) studentMapper.selectCount(wrapper).longValue();
                    detail.put("studentCount", classStudentCount);
                    detail.put("progress", 0);
                    
                    courseDetails.add(detail);
                }
            }
            
            // 7. 构建周课时分布（16周）
            List<Map<String, Object>> weeklyDistribution = new ArrayList<>();
            for (int week = 1; week <= 16; week++) {
                Map<String, Object> weekData = new HashMap<>();
                weekData.put("week", week);
                weekData.put("hours", (int) avgWeeklyHours);
                weeklyDistribution.add(weekData);
            }
            
            // 8. 组装结果
            stats.put("totalHours", totalHours);
            stats.put("courseCount", courseCount);
            stats.put("studentCount", studentCount);
            stats.put("avgWeeklyHours", (int) avgWeeklyHours);
            stats.put("courseDetails", courseDetails);
            stats.put("weeklyDistribution", weeklyDistribution);
            
            System.out.println("统计完成!");
            return stats;
            
        } catch (Exception e) {
            System.err.println("统计工作量失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("统计工作量失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public Map<String, Object> getTeacherTimePreference(Long teacherId) {
        QueryWrapper<TeacherPreference> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id", teacherId)
                   .eq("is_enabled", 1);
        List<TeacherPreference> preferences = teacherPreferenceMapper.selectList(queryWrapper);
        
        Map<String, Object> result = new HashMap<>();
        for (TeacherPreference preference : preferences) {
            result.put(preference.getPreferenceType(), preference.getPreferenceContent());
        }
        
        return result;
    }
    
    @Override
    public boolean setTeacherTimePreference(Long teacherId, Map<String, Object> preferences) {
        try {
            // 删除现有偏好
            QueryWrapper<TeacherPreference> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("teacher_id", teacherId);
            teacherPreferenceMapper.delete(deleteWrapper);
            
            // 添加新偏好
            for (Map.Entry<String, Object> entry : preferences.entrySet()) {
                TeacherPreference preference = new TeacherPreference();
                preference.setTeacherId(teacherId);
                preference.setPreferenceType(entry.getKey());
                preference.setPreferenceContent(entry.getValue().toString());
                preference.setWeight(5);
                preference.setIsEnabled(1);
                preference.setCreateTime(new Date());
                preference.setUpdateTime(new Date());
                teacherPreferenceMapper.insert(preference);
            }
            
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<Map<String, Object>> getTeacherStudents(Long teacherId, String semester) {
        List<Map<String, Object>> result = new ArrayList<>();
        
        try {
            System.out.println("=== 查询教师学生（区分必修/选修）===");
            System.out.println("教师ID: " + teacherId + ", 学期: " + semester);
            
            // 1. 查询该教师教授的所有课程
            QueryWrapper<Course> courseWrapper = new QueryWrapper<>();
            courseWrapper.eq("teacher_id", teacherId);
            List<Course> courses = courseMapper.selectList(courseWrapper);
            System.out.println("教师教授的课程数量: " + courses.size());
            
            // 2. 区分必修课和选修课
            List<Long> requiredCourseIds = new ArrayList<>();  // 必修课
            List<Long> electiveCourseIds = new ArrayList<>();  // 选修课
            
            for (Course course : courses) {
                if ("选修".equals(course.getCourseType())) {
                    electiveCourseIds.add(course.getCourseId());
                    System.out.println("  - 选修课: " + course.getCourseName() + " (ID: " + course.getCourseId() + ")");
                } else {
                    requiredCourseIds.add(course.getCourseId());
                    System.out.println("  - 必修课: " + course.getCourseName() + " (ID: " + course.getCourseId() + ")");
                }
            }
            
            Set<Long> studentIds = new HashSet<>();  // 用于去重
            
            // 3. 对于选修课：只查询已选课的学生
            if (!electiveCourseIds.isEmpty()) {
                System.out.println("\n📚 处理选修课学生（只返回已选课的学生）");
                QueryWrapper<StudentCourse> scWrapper = new QueryWrapper<>();
                scWrapper.in("course_id", electiveCourseIds)
                         .eq("status", "SELECTED");  // ✅ 只查询已通过审核的
                if (semester != null && !semester.isEmpty()) {
                    scWrapper.eq("semester", semester);
                }
                
                List<StudentCourse> selectedCourses = studentCourseMapper.selectList(scWrapper);
                System.out.println("选修课的选课记录数: " + selectedCourses.size());
                
                for (StudentCourse sc : selectedCourses) {
                    if (sc.getStudentId() != null) {
                        // 确保类型一致（StudentCourse.studentId可能是Long或Integer）
                        Long studentId = (sc.getStudentId() instanceof Long) ? 
                                        (Long) sc.getStudentId() : 
                                        ((Number) sc.getStudentId()).longValue();
                        studentIds.add(studentId);
                    }
                }
                System.out.println("选修课学生ID集合: " + studentIds);
            }
            
            // 4. 对于必修课：查询班级内所有学生（保持原逻辑）
            if (!requiredCourseIds.isEmpty()) {
                System.out.println("\n📖 处理必修课学生（返回班级内所有学生）");
                
                Set<Long> clazzIds = new HashSet<>();
                
                // 通过课程安排查询授课班级
                List<ScheduleListDTO> schedules = scheduleService.getTeacherSchedule(teacherId, semester);
                if (schedules != null) {
                for (ScheduleListDTO schedule : schedules) {
                    if (schedule.getClazzId() != null) {
                        clazzIds.add(schedule.getClazzId());
                    }
                }
            }
            
                // 通过clazz_teacher关联表查询
            QueryWrapper<ClazzTeacher> ctWrapper = new QueryWrapper<>();
            ctWrapper.eq("teacher_id", teacherId);
            List<ClazzTeacher> clazzTeachers = clazzTeacherMapper.selectList(ctWrapper);
                if (clazzTeachers != null) {
                for (ClazzTeacher ct : clazzTeachers) {
                    if (ct.getClazzId() != null) {
                        clazzIds.add(ct.getClazzId());
                        }
                    }
                }
                
                System.out.println("必修课关联的班级IDs: " + clazzIds);
                
                if (!clazzIds.isEmpty()) {
                    QueryWrapper<Student> studentWrapper = new QueryWrapper<>();
                    studentWrapper.in("clazz_id", clazzIds);
                    List<Student> students = studentMapper.selectList(studentWrapper);
                    
                    for (Student student : students) {
                        if (student.getStudentId() != null) {
                            studentIds.add(student.getStudentId().longValue());  // ✅ 转换为Long
                        }
                    }
                    System.out.println("必修课学生数量: " + students.size());
                }
            }
            
            // 5. 如果没有任何学生
            if (studentIds.isEmpty()) {
                System.out.println("⚠️ 没有找到任何学生");
                return result;
            }
            
            // 6. 根据学生ID查询完整学生信息
            System.out.println("\n✅ 最终学生ID集合（去重后）: " + studentIds);
            System.out.println("学生总数: " + studentIds.size());
            
            QueryWrapper<Student> finalWrapper = new QueryWrapper<>();
            finalWrapper.in("student_id", studentIds);
            finalWrapper.orderByAsc("stu_no");
            List<Student> students = studentMapper.selectList(finalWrapper);
            
            // 7. 构建返回数据
            for (Student student : students) {
                Map<String, Object> studentInfo = new HashMap<>();
                studentInfo.put("studentId", student.getStudentId());
                studentInfo.put("stuNo", student.getStuNo());
                studentInfo.put("stuName", student.getStuName());
                studentInfo.put("stuAge", student.getStuAge());
                studentInfo.put("stuSex", student.getStuSex());
                studentInfo.put("stuDept", student.getStuDept());
                studentInfo.put("stuPhone", student.getStuPhone());
                studentInfo.put("stuEmail", student.getStuEmail());
                studentInfo.put("stuQq", student.getStuQq());
                studentInfo.put("stuRemark", student.getStuRemark());
                
                // 获取班级信息
                if (student.getClazzId() != null) {
                    Clazz clazz = clazzMapper.selectById(student.getClazzId());
                    if (clazz != null) {
                        studentInfo.put("clazzId", clazz.getClazzId());
                        studentInfo.put("clazzName", clazz.getClazzName());
                        studentInfo.put("grade", clazz.getGrade());
                        studentInfo.put("dept", clazz.getDept());
                    } else {
                        studentInfo.put("clazzId", student.getClazzId());
                        studentInfo.put("clazzName", "未知班级");
                        studentInfo.put("grade", "");
                        studentInfo.put("dept", student.getStuDept());
                    }
                } else {
                    studentInfo.put("clazzId", null);
                    studentInfo.put("clazzName", "未分配班级");
                    studentInfo.put("grade", "");
                    studentInfo.put("dept", student.getStuDept());
                }
                
                result.add(studentInfo);
            }
            
            System.out.println("📊 最终返回学生总数: " + result.size());
            return result;
        } catch (Exception e) {
            System.err.println("❌ 查询教师学生失败：");
            e.printStackTrace();
            throw new RuntimeException("查询教师学生失败: " + e.getMessage(), e);
        }
    }
    
    // ==================== 成绩管理相关方法实现 ====================
    
    @Override
    public List<Map<String, Object>> getTeacherGrades(Long teacherId, String semester, Long courseId, 
                                                      Long clazzId, String studentName, Integer status) {
        try {
            return gradeMapper.getTeacherGradesWithDetails(teacherId, semester, courseId, clazzId, studentName, status);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取成绩列表失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public List<Map<String, Object>> getTeacherCourses(Long teacherId, String semester) {
        try {
            return gradeMapper.getTeacherCourses(teacherId, semester);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取课程列表失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public List<Map<String, Object>> getCourseClasses(Long teacherId, Long courseId, String semester) {
        try {
            System.out.println("=== 获取课程班级列表（区分必修/选修）===");
            System.out.println("教师ID: " + teacherId);
            System.out.println("课程ID: " + courseId);
            System.out.println("学期: " + semester);
            
            // 1. 查询课程类型
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                throw new RuntimeException("课程不存在");
            }
            
            String courseType = course.getCourseType();
            System.out.println("课程类型: " + courseType);
            
            // 2. 如果是选修课，返回对应的实际班级
            if ("选修".equals(courseType)) {
                System.out.println("📚 选修课 - 查找对应的实际班级");
                
                List<Map<String, Object>> result = new ArrayList<>();
                
                // 查找该选修课对应的班级（班级名应包含课程名）
                QueryWrapper<Clazz> clazzWrapper = new QueryWrapper<>();
                clazzWrapper.like("clazz_name", course.getCourseName())
                           .like("clazz_name", "选修");  // 通过班级名称包含"选修"来识别
                List<Clazz> clazzes = clazzMapper.selectList(clazzWrapper);
                
                System.out.println("找到选修课班级数: " + clazzes.size());
                
                if (!clazzes.isEmpty()) {
                    // 有对应的实际班级
                    for (Clazz clazz : clazzes) {
                        // 查询该课程的已选课学生数量
                        QueryWrapper<StudentCourse> scWrapper = new QueryWrapper<>();
                        scWrapper.eq("course_id", courseId)
                                 .eq("status", "SELECTED");
                        if (semester != null && !semester.isEmpty()) {
                            scWrapper.eq("semester", semester);
                        }
                        
                        Long studentCount = studentCourseMapper.selectCount(scWrapper);
                        
                        Map<String, Object> classInfo = new HashMap<>();
                        classInfo.put("clazzId", clazz.getClazzId());
                        classInfo.put("clazzName", clazz.getClazzName());
                        classInfo.put("studentCount", studentCount);
                        classInfo.put("grade", clazz.getGrade());
                        classInfo.put("dept", clazz.getDept());
                        
                        result.add(classInfo);
                        System.out.println("✅ 返回实际班级: " + clazz.getClazzName() + "，学生数: " + studentCount);
                    }
                } else {
                    System.out.println("⚠️ 该选修课没有对应的班级，请先在数据库中创建班级");
                }
                
                return result;
            } 
            // 3. 如果是必修课，返回实际的班级列表（原有逻辑）
            else {
                System.out.println("📖 必修课 - 返回实际班级列表");
                List<Map<String, Object>> result = gradeMapper.getCourseClasses(teacherId, courseId, semester);
                System.out.println("✅ 返回班级数: " + result.size());
                return result;
            }
        } catch (Exception e) {
            System.err.println("❌ 获取班级列表失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("获取班级列表失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public List<Map<String, Object>> getClassStudents(Long clazzId, Long courseId) {
        try {
            System.out.println("=== 获取班级学生（区分必修/选修）===");
            System.out.println("班级ID: " + clazzId);
            System.out.println("课程ID: " + courseId);
            
            // 1. 查询课程类型
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                throw new RuntimeException("课程不存在");
            }
            
            String courseType = course.getCourseType();
            System.out.println("课程类型: " + courseType);
            
            // 2. 如果是选修课，只返回已选课的学生（不看 clazz 表的关联）
            if ("选修".equals(courseType)) {
                System.out.println("📚 选修课 - 只返回已选课的学生（从 student_course 表查询）");
                
                List<Map<String, Object>> result = new ArrayList<>();
                
                // 查询该课程的已选课学生
                QueryWrapper<StudentCourse> scWrapper = new QueryWrapper<>();
                scWrapper.eq("course_id", courseId)
                         .eq("status", "SELECTED");  // 只查询已通过审核的
                
                List<StudentCourse> selectedCourses = studentCourseMapper.selectList(scWrapper);
                System.out.println("已选课学生数: " + selectedCourses.size());
                
                for (StudentCourse sc : selectedCourses) {
                    Long studentId = (sc.getStudentId() instanceof Long) ? 
                                    (Long) sc.getStudentId() : 
                                    ((Number) sc.getStudentId()).longValue();
                    
                    Student student = studentMapper.selectById(studentId);
                    if (student != null) {
                        Map<String, Object> studentInfo = new HashMap<>();
                        studentInfo.put("studentId", student.getStudentId());
                        studentInfo.put("stuNo", student.getStuNo());
                        studentInfo.put("stuName", student.getStuName());
                        studentInfo.put("stuSex", student.getStuSex());
                        studentInfo.put("stuAge", student.getStuAge());
                        studentInfo.put("clazzId", student.getClazzId());
                        
                        // 获取班级信息
                        if (student.getClazzId() != null) {
                            Clazz clazz = clazzMapper.selectById(student.getClazzId());
                            if (clazz != null) {
                                studentInfo.put("clazzName", clazz.getClazzName());
                            }
                        }
                        
                        result.add(studentInfo);
                        System.out.println("  - " + student.getStuName() + " (学号: " + student.getStuNo() + ", 班级: " + studentInfo.get("clazzName") + ")");
                    }
                }
                
                System.out.println("✅ 最终返回选修课学生: " + result.size() + "人");
                return result;
            } 
            // 3. 如果是必修课，返回整个班级的学生（原有逻辑）
            else {
                System.out.println("📖 必修课 - 返回整个班级的学生");
                List<Map<String, Object>> result = gradeMapper.getClassStudents(clazzId, courseId);
                System.out.println("✅ 返回班级学生: " + result.size() + "人");
                return result;
            }
        } catch (Exception e) {
            System.err.println("❌ 获取学生列表失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("获取学生列表失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public boolean addGrade(Grade grade) {
        try {
            // 设置默认值
            if (grade.getInputTime() == null) {
                grade.setInputTime(new Date());
            }
            if (grade.getUpdateTime() == null) {
                grade.setUpdateTime(new Date());
            }
            if (grade.getStatus() == null) {
                grade.setStatus(1);
            }
            
            return gradeMapper.insert(grade) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("添加成绩失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public boolean updateGrade(Grade grade) {
        try {
            grade.setUpdateTime(new Date());
            return gradeMapper.updateById(grade) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("更新成绩失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public boolean deleteGrade(Long gradeId) {
        try {
            // 软删除：将status设为0
            Grade grade = gradeMapper.selectById(gradeId);
            if (grade != null) {
                grade.setStatus(0);
                grade.setUpdateTime(new Date());
                return gradeMapper.updateById(grade) > 0;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("删除成绩失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public boolean batchAddGrades(List<Grade> grades) {
        try {
            Date now = new Date();
            int insertCount = 0;
            int updateCount = 0;
            
            for (Grade grade : grades) {
                // 查询是否已存在该成绩记录（根据唯一索引：student_id + course_id + semester）
                QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("student_id", grade.getStudentId())
                           .eq("course_id", grade.getCourseId())
                           .eq("semester", grade.getSemester());
                
                Grade existingGrade = gradeMapper.selectOne(queryWrapper);
                
                if (existingGrade != null) {
                    // 已存在，执行更新
                    System.out.println("更新成绩：学生ID=" + grade.getStudentId() + 
                                     ", 课程ID=" + grade.getCourseId() + 
                                     ", 学期=" + grade.getSemester());
                    
                    // 保留原有的 gradeId 和 inputTime
                    grade.setGradeId(existingGrade.getGradeId());
                    grade.setInputTime(existingGrade.getInputTime());
                    grade.setUpdateTime(now);
                    if (grade.getStatus() == null) {
                        grade.setStatus(1);
                    }
                    
                    gradeMapper.updateById(grade);
                    updateCount++;
                } else {
                    // 不存在，执行插入
                    System.out.println("插入成绩：学生ID=" + grade.getStudentId() + 
                                     ", 课程ID=" + grade.getCourseId() + 
                                     ", 学期=" + grade.getSemester());
                    
                if (grade.getInputTime() == null) {
                    grade.setInputTime(now);
                }
                if (grade.getUpdateTime() == null) {
                    grade.setUpdateTime(now);
                }
                if (grade.getStatus() == null) {
                    grade.setStatus(1);
                }
                    
                gradeMapper.insert(grade);
                    insertCount++;
                }
            }
            
            System.out.println("批量操作完成：新增 " + insertCount + " 条，更新 " + updateCount + " 条");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("批量添加成绩失败: " + e.getMessage(), e);
        }
    }
    
    // ==================== 选课审核相关方法实现 ====================
    
    @Override
    public List<Map<String, Object>> getPendingCourseApplications(Long teacherId, String semester) {
        System.out.println("=== 获取待审核的选课申请 ===");
        System.out.println("教师ID: " + teacherId);
        System.out.println("学期: " + semester);
        
        try {
            // 1. 查询该教师教授的课程
            QueryWrapper<Course> courseWrapper = new QueryWrapper<>();
            courseWrapper.eq("teacher_id", teacherId);
            List<Course> courses = courseMapper.selectList(courseWrapper);
            
            if (courses.isEmpty()) {
                System.out.println("该教师没有教授任何课程");
                return new ArrayList<>();
            }
            
            List<Long> courseIds = courses.stream()
                    .map(Course::getCourseId)
                    .collect(java.util.stream.Collectors.toList());
            
            // 2. 查询这些课程的待审核选课申请
            QueryWrapper<StudentCourse> scWrapper = new QueryWrapper<>();
            scWrapper.in("course_id", courseIds)
                     .eq("status", "PENDING");
            if (semester != null && !semester.isEmpty()) {
                scWrapper.eq("semester", semester);
            }
            scWrapper.orderByDesc("select_time");
            
            List<StudentCourse> pendingApplications = studentCourseMapper.selectList(scWrapper);
            System.out.println("找到待审核申请: " + pendingApplications.size() + " 条");
            
            // 3. 构建返回数据
            List<Map<String, Object>> result = new ArrayList<>();
            for (StudentCourse sc : pendingApplications) {
                Map<String, Object> appInfo = new HashMap<>();
                
                // 选课申请信息
                appInfo.put("studentCourseId", sc.getId());
                appInfo.put("selectTime", sc.getSelectTime());
                appInfo.put("semester", sc.getSemester());
                appInfo.put("status", sc.getStatus());
                
                // 学生信息
                Student student = studentMapper.selectById(sc.getStudentId());
                if (student != null) {
                    appInfo.put("studentId", student.getStudentId());
                    appInfo.put("studentNo", student.getStuNo());
                    appInfo.put("studentName", student.getStuName());
                    appInfo.put("studentSex", student.getStuSex());
                    appInfo.put("studentPhone", student.getStuPhone());
                    appInfo.put("clazzId", student.getClazzId());
                    
                    // 班级信息
                    if (student.getClazzId() != null) {
                        Clazz clazz = clazzMapper.selectById(student.getClazzId());
                        if (clazz != null) {
                            appInfo.put("clazzName", clazz.getClazzName());
                        }
                    }
                }
                
                // 课程信息
                Course course = courseMapper.selectById(sc.getCourseId());
                if (course != null) {
                    appInfo.put("courseId", course.getCourseId());
                    appInfo.put("courseNo", course.getCourseNo());
                    appInfo.put("courseName", course.getCourseName());
                    appInfo.put("courseType", course.getCourseType());
                    appInfo.put("credit", course.getCredit());
                }
                
                result.add(appInfo);
            }
            
            return result;
        } catch (Exception e) {
            System.err.println("❌ 获取待审核选课申请失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("获取待审核选课申请失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public boolean reviewCourseApplication(Long studentCourseId, boolean approved, String rejectReason) {
        System.out.println("=== 审核选课申请 ===");
        System.out.println("选课记录ID: " + studentCourseId);
        System.out.println("审核结果: " + (approved ? "通过" : "拒绝"));
        if (!approved && rejectReason != null) {
            System.out.println("拒绝原因: " + rejectReason);
        }
        
        try {
            StudentCourse studentCourse = studentCourseMapper.selectById(studentCourseId);
            if (studentCourse == null) {
                System.out.println("⚠️ 选课记录不存在");
                return false;
            }
            
            if (!"PENDING".equals(studentCourse.getStatus())) {
                System.out.println("⚠️ 该申请已被处理，当前状态: " + studentCourse.getStatus());
                return false;
            }
            
            if (approved) {
                // 通过：将状态改为 SELECTED
                studentCourse.setStatus("SELECTED");
                studentCourse.setUpdateTime(new Date());
                System.out.println("✅ 选课申请已通过");
            } else {
                // 拒绝：将状态改为 REJECTED
                studentCourse.setStatus("REJECTED");
                studentCourse.setUpdateTime(new Date());
                // 可以考虑添加一个拒绝原因字段
                System.out.println("❌ 选课申请已拒绝");
            }
            
            int result = studentCourseMapper.updateById(studentCourse);
            return result > 0;
        } catch (Exception e) {
            System.err.println("❌ 审核选课申请失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("审核选课申请失败: " + e.getMessage(), e);
        }
    }
}


